#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //write read close 函数的头文件
#include <fcntl.h>  //open函数以及其对应的宏
#include <errno.h>  //perror函数头文件
#define err_exit(MSG) (perror(MSG), exit(-1))
/*
*****************函数功能：实现文件复制**********************
*/
void copy(int fold, int fnew);
void main(int argc, char *args[])
{
    int fold, fnew; //文件描述符
    //判断参数
    if (argc != 3)
    {
        err_exit("argument error!\n");
    }
    //打开原文件
    fold = open(args[1], O_RDONLY);
    if (fold == -1)
    {
        err_exit("cannot open file!\n");
    }
    //打开新文件
    fnew = open(args[2], O_CREAT | O_WRONLY, 0666);
    if (fnew == -1)
    {
        err_exit("cannot create file!\n");
    }
    //文件拷贝
    copy(fold, fnew);
    //关闭文件
    close(fold);
    close(fnew);
}

void copy(int fold, int fnew)
{
    char buffer[2048]; //2K大小的buffer
    int cnt = 0;       //缓冲区中的字符数
    //利用循环执行拷贝
    while ((cnt = read(fold, buffer, sizeof(buffer))) > 0)
    {
        write(fnew, buffer, cnt);
    }
}
